package core

import (
	"log"
	"net/http"
	"time"
)

type HttpRouter struct {
	router map[string]map[string]http.HandlerFunc
}

func (c *HttpRouter) HandleFunc(method, pattern string, handle http.HandlerFunc) {
	if method == "" {
		panic("method can't be null")
	}

	if pattern == "" {
		panic("Pattern can not be null!")
	}

	if  _, ok := c.router[method][pattern]; ok {
		panic("Pattern Exists!")
	}

	if c.router == nil {
		c.router = make(map[string]map[string]http.HandlerFunc)
	}

	if c.router[method] == nil {
		c.router[method] = make(map[string]http.HandlerFunc)
	}

	c.router[method][pattern] = handle
}

func (c *HttpRouter) ServeHTTP(w http.ResponseWriter, r * http.Request) {
	if f, ok := c.router[r.Method][r.URL.Path]; ok {
		func (handle http.Handler) {
			start := time.Now()
			f.ServeHTTP(w, r)
			log.Printf(" %s 请求 [%s] 完成时间为 : %v\n", r.Method, r.URL.String(), time.Since(start))
		}(f)
	}
}

func (c *HttpRouter) GET(pattern string, handler http.HandlerFunc) {
	c.HandleFunc("GET", pattern, handler)
}

func (c *HttpRouter) POST(pattern string, handler http.HandlerFunc) {
	c.HandleFunc("POST", pattern, handler)
}

func (c *HttpRouter) PUT(pattern string, handler http.HandlerFunc) {
	c.HandleFunc("PUT", pattern, handler)
}

func (c *HttpRouter) DELETE(pattern string, handler http.HandlerFunc) {
	c.HandleFunc("DELETE", pattern, handler)
}

func (c *HttpRouter) OPTIONS(pattern string, handler http.HandlerFunc) {
	c.HandleFunc("OPTIONS", pattern, handler)
}

func (c *HttpRouter) HEAD(pattern string, handler http.HandlerFunc) {
	c.HandleFunc("HEAD", pattern, handler)
}

func NewRouter() *HttpRouter {
	return new(HttpRouter)
}